<h2>Why is this an issue?</h2>
<p>Catching <code>NullReferenceException</code> is generally considered a bad practice because it can hide bugs in your code. Instead of catching this
exception, you should aim to prevent it. This makes your code more robust and easier to understand. In addition, constantly catching and handling
<code>NullReferenceException</code> can lead to performance issues. Exceptions are expensive in terms of system resources, so they should be used
cautiously and only for exceptional conditions, not for regular control flow.</p>
<h2>How to fix it</h2>
<p>Instead of catching NullReferenceException, it’s better to prevent it from happening in the first place. You can do this by using null checks or
null conditional operators (<code>?.</code>) before accessing members of an object.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
public int GetLengthPlusTwo(string str)
{
    try
    {
        return str.Length + 2;
    }
    catch (NullReferenceException e)
    {
        return 2;
    }
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
public int GetLengthPlusTwo(string str)
{
    if (str is null)
    {
        return 2;
    }
    return str.Length + 2;
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
  <li> CWE - <a href="https://cwe.mitre.org/data/definitions/395">CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference</a>
  </li>
  <li> Microsoft Learn - <a href="https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception">NullReferenceException class</a> </li>
  <li> Microsoft Learn - <a
  href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-">Null-conditional operators ?. and ?[]</a> </li>
</ul>

